import React from 'react';
import { useLocation, Link as RouterLink } from 'react-router-dom';
import {
  Breadcrumbs,
  Link,
  Typography,
  Box,
  useTheme,
} from '@mui/material';
import {
  NavigateNext,
  Home,
} from '@mui/icons-material';

import { BreadcrumbItem } from '@/types';
import { pagesMeta } from '@/routes';

interface PageBreadcrumbsProps {
  items?: BreadcrumbItem[];
}

export const PageBreadcrumbs: React.FC<PageBreadcrumbsProps> = ({ items }) => {
  const theme = useTheme();
  const location = useLocation();

  // 如果没有传入面包屑，则根据路由自动生成
  const getBreadcrumbsFromRoute = (): BreadcrumbItem[] => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const breadcrumbs: BreadcrumbItem[] = [
      { label: '首页', path: '/', icon: 'Home' },
    ];

    let currentPath = '';
    for (const segment of pathSegments) {
      currentPath += `/${segment}`;
      
      // 查找对应的页面元信息
      const meta = Object.values(pagesMeta).find(m => 
        m.breadcrumbs?.some(b => b.path === currentPath)
      );
      
      if (meta) {
        const breadcrumb = meta.breadcrumbs?.find(b => b.path === currentPath);
        if (breadcrumb) {
          breadcrumbs.push(breadcrumb);
        }
      } else {
        // 如果没有找到元信息，使用默认的标签
        const label = segment.charAt(0).toUpperCase() + segment.slice(1);
        breadcrumbs.push({ label, path: currentPath });
      }
    }

    return breadcrumbs;
  };

  const breadcrumbItems = items || getBreadcrumbsFromRoute();

  // 如果只有一个项目（首页），不显示面包屑
  if (breadcrumbItems.length <= 1) {
    return null;
  }

  const renderBreadcrumbItem = (item: BreadcrumbItem, index: number) => {
    const isLast = index === breadcrumbItems.length - 1;
    
    if (isLast || !item.path) {
      return (
        <Typography
          key={index}
          color="text.primary"
          sx={{
            display: 'flex',
            alignItems: 'center',
            fontWeight: 500,
            fontSize: '0.875rem',
          }}
        >
          {item.icon && item.icon === 'Home' && (
            <Home sx={{ mr: 0.5, fontSize: 16 }} />
          )}
          {item.label}
        </Typography>
      );
    }

    return (
      <Link
        key={index}
        component={RouterLink}
        to={item.path}
        underline="hover"
        color="inherit"
        sx={{
          display: 'flex',
          alignItems: 'center',
          fontSize: '0.875rem',
          '&:hover': {
            color: 'primary.main',
          },
        }}
      >
        {item.icon && item.icon === 'Home' && (
          <Home sx={{ mr: 0.5, fontSize: 16 }} />
        )}
        {item.label}
      </Link>
    );
  };

  return (
    <Box sx={{ mb: 2 }}>
      <Breadcrumbs
        separator={<NavigateNext fontSize="small" />}
        aria-label="breadcrumb"
        sx={{
          '& .MuiBreadcrumbs-separator': {
            color: 'text.secondary',
          },
        }}
      >
        {breadcrumbItems.map(renderBreadcrumbItem)}
      </Breadcrumbs>
    </Box>
  );
};